﻿namespace FFF.Test.Application.DomainServices.FW
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    using Abp.Domain.Services;
    using Abp.Domain.Uow;
    using Abp.EntityFrameworkCore.Uow;
    using Abp.EntityFrameworkCore;
    using AutoMapper;
    using Abp.UI;
    using Ydm.Helper;
    using Ydm.Extensions;
    using Microsoft.EntityFrameworkCore;
    using AutoMapper.QueryableExtensions;
    using FFF.Test.DataAccess.Framework;
    using FFF.Test.Application.Repositories.FW;
    using FFF.Test.Entity.FW;
    using FFF.Test.Entity.FW.Dto;
    using FFF.Test.Entity.FW.View;

    /// <summary>
    /// 功能表(树)领域层服务接口
    /// </summary>
    public class FWFunctionDomainService : YdmAbpDomainServiceBase, IFWFunctionDomainService
    {
        /// <summary>
        /// 功能表(树)仓储
        /// </summary>
        private readonly IFWFunctionRepository _fWFunctionRepository;

        /// <summary>
        /// Initializes a new instance of the <see cref="FWFunctionDomainService"/> class.
        /// 功能表(树)领域层操作
        /// </summary>
        /// <param name="fWFunctionRepository">功能表(树)仓储</param>
        public FWFunctionDomainService(
            IFWFunctionRepository fWFunctionRepository
        )
        {
            this._fWFunctionRepository = fWFunctionRepository;
        }

        /// <summary>
        /// 1.002 获取菜单(于大明)
        /// </summary>
        /// <param name="inDto">获取菜单输入dto</param>
        /// <returns>获取菜单输出dto</returns>
        public async Task<GetFunctionMenuOutDto> GetFunctionMenuAsync(GetFunctionMenuInDto inDto)
        {
            var viewFunction = this._fWFunctionRepository.GetView();
            GetFunctionMenuOutDto result = new GetFunctionMenuOutDto();
            result.MenuDtos = new List<FunctionMenuDto>();

            // 找出Function中所有未禁用的菜单
            IQueryable<ViewFWFunction> menuQuery = viewFunction.Where(x => x.FunctionIsDisable != 1);

            if (inDto.IsTopMenu == 1)
            {
                menuQuery = menuQuery.Where(x => x.ParentGUID == null && x.ModuleGUID == inDto.FunctionGUID);
            }
            else
            {
                menuQuery = menuQuery.Where(x => x.ParentGUID == inDto.FunctionGUID);
            }

            // 根据编码排序
            menuQuery = menuQuery.OrderBy(x => x.OrderCode).OrderBy(x => x.FullCode);
            List<ViewFWFunction> menuLst = await menuQuery.ToListAsync();
            foreach (ViewFWFunction menu in menuLst)
            {
                FunctionMenuDto menuDto = new FunctionMenuDto()
                {
                    Id = menu.Id,
                    IconCls = menu.Icon,
                    Pid = menu.ParentGUID,
                    State = "open",
                    Text = menu.FunctionName,
                    Url = menu.FunctionUrl
                };
                result.MenuDtos.Add(menuDto);
            }

            return result;
        }
    }
}
